import { Text, useMessage } from 'alemonjs'
import { selects, validate } from '@src/apps/index'
import { user } from '@src/db/src/models/user/user'
import { main_story } from '@src/db/src/models/stroy/main_story'
import { qidToUid } from '@src/apps/tools/qid_goto_uid'

export const regular = /^(!|！|\/)?(跳过|种子)/

const response = onResponse(selects, async e => {
  const [message] = useMessage(e)
  const userId = await qidToUid(e.UserId ?? e.UserKey)

  // 获取用户信息
  const userInfo = await user.findOneValue({ where: { uid: userId } })
  if (!userInfo) {
    message.send(format(Text('\n未找到用户信息。')))
    return
  }

  // 只允许 status=0 且 schedule='初始0' 的用户触发
  if (userInfo.status !== 0 || String(userInfo.schedule) !== '初始0') {
    return
  }

  const msg = e.MessageText || ''
  const match = /^\/?(跳过|种子)\s*(\d+)?$/.exec(msg)
  let storyId: number

  if (match) {
    if (match[1] === '种子' && match[2]) {
      // /种子+数字，直接用数字
      storyId = Number(match[2])
    } else if (match[1] === '跳过') {
      // /跳过，随机1-9
      // storyId = Math.floor(Math.random() * 9) + 1
      storyId = 1
    } else {
      message.send(
        format(Text('\n指令格式错误。\n请回复[/种子+数字]或[/跳过]'))
      )
      return
    }
  } else {
    message.send(format(Text('\n指令格式错误。\n请回复[/种子+数字]或[/跳过]')))
    return
  }

  // 查询剧情
  const storyKey = `初始${storyId}`
  const storyInfo = await main_story.findOneValue({
    where: { story_id: storyKey }
  })
  if (!storyInfo) {
    message.send(format(Text('\n未找到对应剧情，请检查种子编号或联系管理员。')))
    return
  }

  // 将 storyKey 写入用户的 schedule 字段
  await user.update({ schedule: storyKey }, { where: { uid: userId } })

  // 发送剧情内容
  let content = `\n【${storyInfo.title}】\n${storyInfo.content}`
  if (
    storyInfo.options &&
    Array.isArray(storyInfo.options) &&
    storyInfo.options.length > 0
  ) {
    content += '\n——————————————\n'
    content += storyInfo.options
      .map((opt: any, idx: number) => `[${idx + 1}] ${opt.text}`)
      .join('\n')
    content += '\n——————————————\n发送[选择+数字]进行'
  }
  message.send(format(Text(content)))
})

export default onResponse(selects, [validate, response.current])
